package org.goj.management.controller;

import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.goj.common.entity.management.News;
import org.goj.common.entity.user.Topic;
import org.goj.common.model.Result;
import org.goj.management.service.NewsService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 新闻表 前端控制器
 * </p>
 *
 * @author CK
 * @since 2020-12-02
 */
@RestController
@RequestMapping("/news")
public class NewsController {

    @Resource
    private NewsService newsService;

    /**
     * 查询前五条公告
     *
     * @return Result<Page < News>>
     * @author CK
     * @date 2021/4/11 15:00
     */
    @GetMapping("/listNews")
    public Result<Page<News>> listNews() {
        Page<News> page = newsService.listNews();
        return Result.succeed("查询新闻信息成功", page);
    }

    /**
     * 管理员查询公告
     *
     * @param newsId 公告ID
     * @return Result<List < Topic>>
     * @author CK
     * @date 2021/4/11 16:54
     */
    @GetMapping("/adminListNews")
    public Result<List<News>> adminListNews(
            @RequestParam(value = "newsId", required = false, defaultValue = "-1") Integer newsId) {
        List<News> list = newsService.adminListNews(newsId);
        if (newsId != -1) {
            Assert.isTrue(list.size() == 1, "查询公告信息失败");
        }
        return Result.succeed("查询公告信息成功", list);
    }

    /**
     * 插入或更新公告
     *
     * @param newsId 公告ID
     * @param userId 用户ID
     * @param title 标题
     * @param status 状态
     * @param content 内容
     * @return Result<Boolean>
     * @author CK
     * @date 2021/4/11 17:42
     */
    @PostMapping("/insertNews")
    public Result<Boolean> insertNews(
            @RequestParam(value = "newsId", required = false, defaultValue = "-1") Integer newsId,
            @RequestParam(value = "userId") Integer userId,
            @RequestParam(value = "title") String title,
            @RequestParam(value = "status") Integer status,
            @RequestParam(value = "content") String content) {
        News news = new News();
        if (newsId != -1) {
            news.setNewsId(newsId);
        }
        news.setUserId(userId).setTitle(title).setStatus(status).setContent(content).setTime(new Date());
        boolean flag = newsService.saveOrUpdate(news);
        Assert.isTrue(flag, newsId == -1 ? "插入公告信息失败" : "更新公告信息失败");
        return Result.succeed(newsId == -1 ? "插入公告信息成功" : "更新公告信息成功", true);
    }

    /**
     * 管理员删除公告
     *
     * @param newsId 公告ID
     * @return Result<Boolean>
     * @author CK
     * @date 2021/4/11 18:11
     */
    @PostMapping("/deleteNews")
    public Result<Boolean> deleteNews(Integer newsId) {
        boolean flag = newsService.removeById(newsId);
        Assert.isTrue(flag, "删除公告失败");
        return Result.succeed("删除公告成功", flag);
    }

}

